package hn.cch.transaction;


import hn.cch.entity.Order;
import hn.cch.service.OrderService;
import hn.cch.util.DateUtil;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;


@Service
public class LoggerService {


    @Autowired
    private LoggerRepository loggerRepository;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;




    public void beforeOrder(Order order){
        String txid = UUID.randomUUID().toString();
        rocketMQTemplate.sendMessageInTransaction("logger-group", "logger-topic",
                MessageBuilder.withPayload(order).setHeader("txid", txid).build(), order);


    }

    @Transactional
    public void createOrder(String txid, Order order){

        orderService.save(order);

        LoggerMessage loggerMessage = new LoggerMessage();
        loggerMessage.setId(txid);
        loggerMessage.setInfo("order save yes");
        loggerMessage.setTime(DateUtil.toText("yyyy-MM-dd HH:mm:ss", new Date()));
        loggerRepository.save(loggerMessage);
    }
}
